<script lang="ts" setup>
import type { SmsClientType } from '@/apis/sms-setting'
import type { Rule } from 'ant-design-vue/es/form'
import { getUserCenterSmsClientPropertiesConfig, updateUserCenterSmsClientPropertiesConfig } from '@/apis/sms-setting'
import useRequest from '@/hooks/useRequest'
import { message, Modal } from 'ant-design-vue'

const formRef = ref()

const formState = reactive<SmsClientType>({
  addr: '',
  appId: '',
  appSecret: '',
})

const rules: Record<string, Rule[]> = {
  addr: [{ required: true, message: '请输入短信服务地址', trigger: 'change' }],
  appId: [{ required: true, message: '请输入短信应用ID', trigger: 'change' }],
  appSecret: [{ required: true, message: '请输入短信应用密钥', trigger: 'change' }],
}

async function onSave() {
  try {
    await formRef.value.validate()
    Modal.confirm({
      title: '提示',
      content: '更新配置后，系统调用将会实时更新，请谨慎操作。',
      onOk() {
        return new Promise<void>(async (resolve, reject) => {
          try {
            await updateUserCenterSmsClientPropertiesConfig(formState)
            message.success('更新成功')
            resolve()
          }
          catch (error) {
            message.error((error as Error).message)
            reject(error)
          }
        })
      },
      onCancel() {},
    })
  }
  catch (error) {
    console.log(error)
  }
}

const { run, data, loading } = useRequest<SmsClientType>(getUserCenterSmsClientPropertiesConfig)

onMounted(async () => {
  try {
    await run()
    formState.addr = data.value?.addr || ''
    formState.appId = data.value?.appId || ''
    formState.appSecret = data.value?.appSecret || ''
  }
  catch (error) {
    console.log(error)
  }
})
</script>

<template>
  <div class="w-50% margin-auto mt-50px">
    <a-spin :spinning="loading">
      <a-form
        ref="formRef"
        :model="formState"
        size="large"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 14 }"
        :rules="rules"
      >
        <a-form-item
          label="短信服务地址"
          name="addr"
        >
          <a-input v-model:value="formState.addr" placeholder="请输入短信服务地址" />
        </a-form-item>

        <a-form-item
          label="短信应用ID"
          name="appId"
        >
          <a-input v-model:value="formState.appId" placeholder="请输入短信应用ID" />
        </a-form-item>
        <a-form-item
          label="短信应用密钥"
          name="appSecret"
        >
          <a-input-password v-model:value="formState.appSecret" placeholder="请输入短信应用密钥" />
        </a-form-item>

        <a-form-item class="text-right" :wrapper-col="{ offset: 6, span: 14 }">
          <a-button type="primary" @click="onSave">
            保存
          </a-button>
        </a-form-item>
      </a-form>
    </a-spin>
  </div>
</template>
